package JsonInterface.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) throws IOException {
        int port = 40001;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            while (true) {
                Socket clientSocket = serverSocket.accept();
                // 为每个客户端连接创建一个新线程
                new Thread(new ClientHandler(clientSocket)).start();
            }
        } catch (IOException e) {
            System.err.println("服务器异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

class ClientHandler implements Runnable {
    private Socket clientSocket;

    public ClientHandler(Socket socket) {
        this.clientSocket = socket;
    }

    @Override
    public void run() {
        try {
            System.out.println("客户端连接: " + clientSocket.getInetAddress().getHostAddress());
            InputStream inputStream = clientSocket.getInputStream();
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            out.println("111");  // 向客户端发送 "111"
            // 关闭连接
            clientSocket.close();
            System.out.println("已发送 '111' 并关闭连接");
        } catch (IOException e) {
            System.err.println("处理客户端异常: " + e.getMessage());
        }
    }
}
